<template>
	<div class="FileUpload">
		<!-- 文件上传组件 -->
		<el-upload :accept="accept" :auto-upload="false" :file-list="fileList" :on-change="handleChange"
			:on-exceed="handleExceed" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" action="string"
			list-type="picture-card" :class="fileList.length>=limit?'disabled':''">
			<i class="el-icon-plus"></i>
		</el-upload>

		<!-- 文件上传进度条 -->
		<el-progress v-if="progress.visible" :percentage="progress.size"></el-progress>
	</div>
</template>

<script>
	let that
	import {
		mapGetters
	} from 'vuex';
	export default {
		name: 'FileUpload',
		components: {},
		computed: {},
		props: {
			accept: {
				type: String,
				required: false,
				default: ".jpg,.jpeg,.png,.rar,.txt,.zip,.doc,.ppt,.xls,.pdf,.docx,.xlsx",
			},
			limit: { //图片列表最大展示几个默认一个
				type: Number,
				default: 1,
			},
		},
		data() {
			return {
				fileList: [], //上传的文件列表(展现在界面的文件列表)
				updateImageIds: [], //选取的图片及附件id列表
				/**
				 * 文件上传进度
				 */
				progress: {
					visible: false,
					size: 0

				}
			};
		},
		mounted() {
			that = this
		},
		methods: {
			//更新进度条
			setProgress(size, show) {
				this.progress = {
					visible: show,
					size
				}
			},
			// 更新上传列表
			setFileList(list) {
				this.fileList = list
			},
			//选取文件
			async handleChange(file, fileList) {
				//限制大小
				if (file.size > 1024 * 1024 * 10) {
					that.$message({
						type: 'warning',
						message: '文件大小超过10M'
					});
					that.fileList = fileList.filter(res => {
						if (res.uid !== file.uid) {
							return res;
						}
					});
				} else {
					//上传文件
					let req = {
						file,
						fileList
					}
					that.fileList=fileList
					that.$emit('upload', req)
				}
			},
			// 移除文件时的钩子
			handleRemove(file, fileList) {
				that.fileList = fileList
				that.updateImageIds = that.updateImageIds.filter(res => {
					if (res !== file.raw.id) {
						return res;
					}
				});
				let req = {
					fileList: fileList,
					updateImageIds: that.updateImageIds
				}
				that.$emit('fileUploadData', req)
			},
			//点击文件时的钩子
			handlePictureCardPreview(file) {
				let index = file.name.lastIndexOf('.')
				let Suffix = file.name.slice(index + 1, file.name.length)
				if (uni.$lizhao.file.lzGetTypeSuffix(Suffix) == 'image') { //如果是图片
					uni.previewImage({
						urls: [file.url],
					});
				} else { //附件在线浏览
					window.open(file.downloadUrl, '_blank');
				}
			},
			//文件超出限制的构子
			handleExceed(files, fileList) {
				// this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
			}
		}
	};
</script>

<style scoped="scoped" lang="scss"></style>
